import { fileURLToPath, URL } from 'node:url'
import { type ConfigEnv, defineConfig, loadEnv, type ProxyOptions, type UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import eslintPlugin from 'vite-plugin-eslint2'
import viteCompression from 'vite-plugin-compression'
import progress from 'vite-plugin-progress'
import skinBuildPlugin from './plugins/rollup-plugin-skin-build/index'
import docsBuildPlugin from './plugins/rollup-plugin-docs-build/index'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import postcssPxtorem from 'postcss-pxtorem'
import { visualizer } from 'rollup-plugin-visualizer'
import transformExternalCDN from 'vite-plugin-external-cdn'

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const env = loadEnv(mode, process.cwd())
  const version: string = process.env.npm_package_version ?? '0.1.0'

  return {
    plugins: [
      vue(),
      // eslint
      eslintPlugin({
        cache: false,
      }),
      // gz
      viteCompression({
        threshold: 10240, // 即10kb以上即会压缩
      }),
      // 进度
      progress(),
      // 皮肤
      skinBuildPlugin(mode),
      // 文档
      docsBuildPlugin(mode),
      // svg图标
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [fileURLToPath(new URL('src/assets/svg', import.meta.url))],
        // 指定symbolId格式
        symbolId: 'icon-[name]',
      }),
      // cdn
      transformExternalCDN({
        prodUrl: '/cdn/{path}', // 根目录 且需要把资源先down下来
        modules: [
          {
            name: 'vue',
            var: 'Vue',
            path: 'dist/vue.global.prod.js',
          },
          {
            name: 'axios',
            var: 'axios',
            path: 'dist/axios.min.js',
          },
          {
            name: 'lodash',
            var: '_',
            path: 'lodash.min.js',
          },
          {
            name: 'element-plus',
            var: 'ElementPlus',
            path: 'dist/index.full.min.js',
          },
          {
            name: 'vue-i18n',
            var: 'VueI18n',
            path: 'dist/vue-i18n.global.prod.js',
          },
          {
            name: 'vue-router',
            var: 'VueRouter',
            path: 'dist/vue-router.global.prod.js',
          },
          {
            name: 'vue-demi',
            var: 'VueDemi',
            path: 'lib/index.iife.js',
          },
          {
            name: 'pinia',
            var: 'Pinia',
            path: 'dist/pinia.iife.prod.js',
          },
          {
            name: 'echarts',
            var: 'echarts',
            path: 'dist/echarts.min.js',
          },
          {
            name: 'zrender',
            var: 'zrender ',
            path: 'dist/zrender.min.js',
          },
        ],
      }),
      // 观察
      visualizer({
        filename: 'analysis-chart.html',
        open: false,
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    build: {
      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        output: {
          chunkFileNames: `static/js/[name]-[hash]-${version}.js`,
          entryFileNames: `static/js/[name]-[hash]-${version}.js`,
          assetFileNames: `static/[ext]/[name]-[hash]-${version}.[ext]`,
        },
      },
    },
    esbuild: {
      drop: mode === 'development' ? [] : ['console', 'debugger'],
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/theme/rootVars.scss" as *;`,
        },
      },
      postcss: {
        plugins: [
          postcssPxtorem({
            rootValue: 192, // 1920/10
            propList: ['*'],
            exclude: (file: string): boolean => {
              return file.includes('docs/cdn')
            },
          }),
        ],
      },
    },
    server: {
      cors: true,
      host: '0.0.0.0',
      open: Boolean(env.VITE_OPEN === 'true'),
      port: Number(env.VITE_PORT),
      proxy: proxySetting,
    },
    define: {
      __APP_VERSION__: JSON.stringify(version),
    },
  }
})
// 代理设置
const proxySetting: Record<string, string | ProxyOptions> = {
  // 用户认证统一登陆
  '/apiLogin': {
    target: 'https://api.linkgapie.com',
    changeOrigin: true, // 允许跨域
    rewrite: (path) => path.replace(/^\/apiLogin/, '/uc/v1/'),
  },
  // 接口地址
  '/api': {
    target: 'https://api.linkgapie.com',
    changeOrigin: true, // 允许跨域
    rewrite: (path) => path.replace(/^\/api/, ''),
  },
}
